/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sdd.plains;

import java.util.HashSet;
import java.util.Iterator;

/**
 *
 * @author Fernando
 */
public class CartPlain {
    
    HashSet hs;
    Long id;
    
    public CartPlain() {
        hs = new HashSet();
    }
    
    public boolean contains(ProductPlain product) {
        Iterator it = hs.iterator();
        CartItem ci;
        while(it.hasNext()) {
            ci = (CartItem) it.next();
            if(ci.equals(product)){
                return true;
            }
        }
        return false;
    }
    
    public void addToCart(CartItem cartItem) {
        hs.add(cartItem);
    }
    
    public void addToCart(ProductPlain product) {
        CartItem cartItem;
        //antes se utilizaba hs.contains(product) pero no funcionaba¿?
        if(this.contains(product)) {
            Iterator it = hs.iterator();
            while(it.hasNext()) {
                cartItem = (CartItem) it.next();
                if(cartItem.equals(product)) {
                    cartItem.setQuantity(cartItem.getQuantity()+1);
                }
            }
        }
        else {
            
            hs.add(new CartItem(product));
        }
    }
    
    public void setQuantity(ProductPlain product, int quantity) {
        CartItem cartItem;
        
        if(quantity <= 0) {
            hs.remove(product);
        }
        else {
            Iterator it = hs.iterator();
            while(it.hasNext()) {
                cartItem = (CartItem) it.next();
                if(cartItem.equals(product)) {
                    cartItem.setQuantity(quantity);
                }
            }
        }
    }
    
    public Iterator iterator() {
        return hs.iterator();
    }
    
    @Override
    public String toString() {
        return hs.toString();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    
}
